package com.kim.androidbase.alarmtimer;

import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.text.format.Time;
import android.util.Log;

public class AlarmTimer {

	private final static String TAG = "AlarmTimer";

	/**
	 * 开启时钟监听
	 * 
	 * @param context
	 * @param targetTimes
	 *            时间点数组
	 * @param action
	 *            要触发的广播动作
	 */
	public final static void startTimerAlarm(Context context,
			Time[] targetTimes, String action) {

		if (targetTimes == null || targetTimes.length == 0) {
			Log.d(TAG, "bad argument:targetTimes ->" + targetTimes);
			return;
		}

		Time current = new Time();
		current.set(System.currentTimeMillis());

		List<Time> effectiveTimes = new ArrayList<Time>();
		for (Time time : targetTimes) {
			if (time.after(current)) {
				effectiveTimes.add(time);
			}
		}

		if (effectiveTimes.size() > 0) {

			AlarmManager alarmManager = (AlarmManager) context
					.getSystemService(Context.ALARM_SERVICE);
			Intent intent = new Intent(action);
			int requestCode = -1;

			for (Time time : effectiveTimes) {
				requestCode = time.hour;
				PendingIntent operation = PendingIntent.getBroadcast(context,
						requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
				alarmManager.set(AlarmManager.RTC_WAKEUP, time.toMillis(true),
						operation);
			}
		}

	}

	/**
	 * 产生时间点
	 * 
	 * @param hour
	 * @param minute
	 * @param second
	 * @return
	 */
	public static final Time generateTime(int hour, int minute, int second) {
		Time time = new Time();

		time.hour = hour;
		time.minute = minute;
		time.second = second;

		return time;
	}

}
